package com.example.controller;

import com.example.entity.RespBean;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * 验证码
 *
 * @author: liu
 * 2022-03-15-20:57
 **/
@Api(tags = "CaptchaController")
@RestController
public class CaptchaController {

    @Autowired
    public DefaultKaptcha defaultKaptcha;

    @ApiOperation(value = "验证码")
//    @GetMapping(value = "/captcha",produces = "image/jpeg")
    @GetMapping(value = "/captcha")
    public RespBean captcha(HttpServletRequest request, HttpServletResponse response){
        System.out.println("接口被调用");
        /*//定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires",0);
        //Set standard HTTP/1.1 no-cache headers
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        //Set IE extended HTTP/1.1 no-cache headers(use addHeader)
        response.addHeader("Cache-Control","post-check=0,pre-check=0");
        //Set standard HTTP/1.1 no-cache header
        response.setHeader("Pragma","no-cache");
        //return a jpeg
        response.setContentType("image/jpeg");*/

        // 开始生成验证码
        String text = defaultKaptcha.createText(); // 获取验证码文本内容
        System.out.println("验证码文本内容：" + text);
        request.getSession().setAttribute("captcha_1", text);
        System.out.println("CaptchaController送参的captcha为：" + request.getSession().getAttribute("captcha_1"));
        BufferedImage image = defaultKaptcha.createImage(text); // 根据文本内容创建图形验证码
//        ServletOutputStream outputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
//            outputStream = response.getOutputStream();
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream); // 输出流输出图片，格式为jpg
            byte[] bytes = outputStream.toByteArray();//转换成字节
            BASE64Encoder encoder = new BASE64Encoder();
            //转换成base64串
            String png_base64 = encoder.encodeBuffer(bytes).trim();
            //删除 \r\n
            png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");
            //返回的字符串头要拼接data:image/jpg;base64,在字符串前面，这样前台就可以直接在img的src里面直接使用该字符串
            String result = "data:image/jpg;base64,"+png_base64;
//            System.out.println(result);
            outputStream.flush();
            return RespBean.success("",result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("接口调用完成");
        return RespBean.error("验证码生成失败");
        //return Result.success(new LoginCodeVO("data:image/jpg;base64,"+png_base64));
        // 生成验证码结束
        // 查看验证码： http://localhost:8081/captcha
        //生成验证码end



    }
}
